package com.gla.interceptor;

import com.gla.exception.CommonException;
import com.gla.util.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object o) throws Exception, CommonException {
        //让OPTION请求通过
        if(req.getMethod().toString().equals("OPTIONS")){
            return true;
        }
        try {
            String token = req.getHeader("Authorization");
            Integer id = JwtUtil.parseToken(token);
            req.setAttribute("UserID", id);
            req.setAttribute("UserToken", token);
        }catch(ExpiredJwtException e) {
            CommonException err = new CommonException("Token超时");
            throw err;
        }
        return true;
    }
}